package com.java46.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.java46.amqp.MessageSender;
import com.java46.entity.GenericResultEntity;
import com.java46.entity.ReservationRecord;
import com.java46.service.ContactService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 预约界面
 */
@Controller
@RequestMapping("/contact")
public class ContactController {
    @Autowired
    private MessageSender messageSender;

    private MessageListener messageListener;
    //创建MQ消息发送
    @Autowired
    private AmqpTemplate amqpTemplate;
    //日志记录
    private Logger logger = LoggerFactory.getLogger(MessageSender.class);
    @Autowired
    private ContactService contactService;

    @RequestMapping(value = "/add", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public String addContact(ReservationRecord record, HttpServletRequest request, HttpServletResponse response, Model model) throws ParseException, IOException {

        List<String> vlist = new ArrayList<String>();

        try {
            //获取下单时间（前）
            Date restime = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            record.setRestime(sdf.format(restime));
            record.setStatus("0");
            contactService.addRecord(record);
            vlist.add("操作成功！");
        } catch (Exception e) {
            vlist.add("数据异常，请稍后再尝试！");
            throw new RuntimeException("数据异常");
        }
        // 2. 创建 ObjectMapper 对象
        ObjectMapper mapper = new ObjectMapper();
        //创建json字符串接收数据
        String jsonStr = mapper.writeValueAsString(vlist);
        messageSender.setAmqpTemplate(amqpTemplate);
        // 设置RoutingKey，匹配message.*即可
        messageSender.setRoutingKey("message.testUser");
        // 发送消息
        messageSender.sendDataToQueue(record.getResname());
        logger.info("to send message:{}", record.getResname());
        return jsonStr;
    }
    @ResponseBody
    @RequestMapping(value = "/get", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public String get(Model model) throws JsonProcessingException {
           GenericResultEntity result = new GenericResultEntity();
           String message = (String) amqpTemplate.receiveAndConvert("testQueue");
           List<String> messageList = new ArrayList<String>();
           messageList.add(message);
           //创建结果实体并赋值
           result.setSuccess(true);
           result.setData(messageList);
           if(message ==null ||"".equals(message)){
               result.setSuccess(false);
           }
        // 2. 创建 ObjectMapper 对象
        ObjectMapper mapper = new ObjectMapper();
        //创建json字符串接收数据
        String jsonStr = mapper.writeValueAsString(result);
        return jsonStr;
    }
}
